package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleConfigService;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.AuthorService;
import com.heima.common.admin.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    AdminFeign adminFeign;

    @Autowired
    AuthorService authorService;

    @Autowired
    ApArticleConfigService apArticleConfigService;

    @Autowired
    ApArticleContentService apArticleContentService;


    /**
     * wmNews 查询
     *
     * @param newsId 文章id
     */
    @GlobalTransactional(rollbackFor = Exception.class, timeoutMills = 300000)
    @Override
    public void publishArticle(Integer newsId) {
        //1. 根据文章id  查询自媒体文章信息
        WmNews wmNews = getWmNews(newsId);
        //2. 根据wmNews 信息封装ApArticle对象
        ApArticle article = parseApArticle(wmNews);
        //3. 保存或修改apArticle对象
        saveOrUpdateApArticle(article);
        //4. 保存配置信息和内容信息
        saveConfigAndContent(article, wmNews);
        //5. 静态化页面
        //6. 修改wmNews的状态 将状态改为9 并设置关联的articleId
        updateWmNews(wmNews, article);
    }

    /**
     * 修改wmNews的状态
     *      将状态改为9
     * @param wmNews
     * @param article
     */
    private void updateWmNews(WmNews wmNews, ApArticle article) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(article.getId());
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程修改自媒体状态失败");
        }
    }

    /**
     * 保存配置和内容信息
     * @param article
     * @param wmNews
     */
    private void saveConfigAndContent(ApArticle article, WmNews wmNews) {
        //1. 保存文章配置信息
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(article.getId());
        config.setIsComment(true);//是否允许评论
        config.setIsForward(true);//是否允许转发
        config.setIsDown(false);//是否下架
        config.setIsDelete(false);//是否删除
        apArticleConfigService.save(config);
        //2. 保存文章内容信息
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(article.getId());
        content.setContent(wmNews.getContent());
        apArticleContentService.save(content);

    }

    /**
     * 保存修改apArticle对象
     * @param article
     */
    private void saveOrUpdateApArticle(ApArticle article) {
        if (article.getId() == null) {
            //保存
            article.setViews(0);
            article.setLikes(0);
            article.setComment(0);
            article.setCollection(0);
            this.save(article);
        } else {
            // 删除关联的文章配置信息 和文章详情信息
            apArticleConfigService.remove(
                    Wrappers.<ApArticleConfig>lambdaQuery()
                            .eq(ApArticleConfig::getArticleId, article.getId())
            );
            apArticleContentService.remove(
                    Wrappers.<ApArticleContent>lambdaQuery()
                            .eq(ApArticleContent::getArticleId, article.getId())
            );

            //修改
            this.updateById(article);

        }

    }


    /**
     * 基于wmNews 封装ApArticle
     * @param wmNews
     * @return
     */
    private ApArticle parseApArticle(WmNews wmNews) {
        //1. 创建article 将wmNews的同名属性拷贝进去
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(wmNews, article);
        //2. 单独设置articleId字段
        article.setId(wmNews.getArticleId());
        //3. 其他要补充的字段 flag layout
        article.setLayout(wmNews.getType());
        article.setFlag((byte) 0);
        //4. 频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (!channelResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程查询频道信息失败");
        }
        AdChannel channel = channelResult.getData();
        article.setChannelName(channel.getName());
        //5. 作者信息
        ApAuthor apAuthor = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        article.setAuthorId(Long.valueOf(apAuthor.getId()));
        article.setAuthorName(apAuthor.getName());
        return article;
    }

    /**
     * 根据id查询自媒体文章信息
     *
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        //1. 先根据id使用feign接口远程查询
        ResponseResult<WmNews> result = wemediaFeign.findWmNewsById(newsId);
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmNews wmNews = result.getData();
        //2. 判断文章是否为null
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3. 判断文章的状态必须是4或者8
        Short status = wmNews.getStatus();
        if (!WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)&&!WemediaConstants.WM_NEWS_AUTHED_STATUS.equals(status)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章的状态  不是审核通过的状态 发布文章失败");
        }
        return wmNews;
    }
}